package com.erp.erp_servers.Blueprint.imp;

import com.erp.erp_dao.Blueprint.BlueprintContentMapper;
import com.erp.erp_dao.Blueprint.IBlueprintDAO;
import com.erp.erp_dao.Blueprint.IBlueprintFileDAO;
import com.erp.erp_dao.Blueprint.IBlueprintProductDAO;
import com.erp.erp_entitys.Blueprint.BlueprintContent;
import com.erp.erp_entitys.Blueprint.BlueprintEntity;
import com.erp.erp_entitys.Blueprint.BlueprintFileEntity;
import com.erp.erp_entitys.Blueprint.BlueprintProductEntity;
import com.erp.erp_entitys.Blueprint.res.AddBlueprintContentRes;
import com.erp.erp_entitys.Blueprint.res.MapDetailArray;
import com.erp.erp_servers.Blueprint.IBlueprintService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class ImpBlueprintService implements IBlueprintService {
    @Autowired
    IBlueprintDAO blueprintDAO;
    @Autowired
    IBlueprintProductDAO blueprintProductDAO;
    @Autowired
    IBlueprintFileDAO blueprintFileDAO;

    @Autowired
    BlueprintContentMapper blueprintContentDao;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return blueprintDAO.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(BlueprintEntity blueprint) {
        return blueprintDAO.insert(blueprint);
    }

    @Override
    public int insertSelective(BlueprintEntity blueprint) {
        return blueprintDAO.insertSelective(blueprint);
    }

    @Override
    public BlueprintEntity selectByPrimaryKey(Integer id) {
        return blueprintDAO.selectByPrimaryKey(id);
    }


    @Override
    public int updateByPrimaryKeySelective(BlueprintEntity blueprint) {
        return blueprintDAO.updateByPrimaryKeySelective(blueprint);
    }

    @Override
    public int updateByPrimaryKey(BlueprintEntity blueprint) {
        return blueprintDAO.updateByPrimaryKey(blueprint);
    }

    @Override
    public PageInfo<BlueprintEntity> selectByPage(Map<String,String> map) {
        List<BlueprintEntity> blueprintList = blueprintDAO.selectByPage(map);
        //获取分页信息
        PageInfo pageInfo = new PageInfo(blueprintList);
        if(CollectionUtils.isEmpty(blueprintList)){
            pageInfo.setList(null);
            return pageInfo;
        }
        pageInfo.setList(blueprintList);
        return pageInfo;
    }

    @Override
    public List<BlueprintEntity> selectBlueprintList(Map<String,Object> map) {
        return blueprintDAO.selectBlueprintList(map);
    }

    @Override
    public int updateBoxStatusBykey(Map<String,Object> map) {
        return blueprintDAO.updateBoxStatusBykey(map);
    }

    @Override
    public List<BlueprintEntity> selectByIdList(List<String> list) {
        return blueprintDAO.selectByIdList(list);
    }

    @Override
    public int updateBoxStatus(List<BlueprintEntity> list) {
        return blueprintDAO.updateBoxStatus(list);
    }

    @Override
    public int deleteByIdList(List<String> idList) {
        return blueprintDAO.deleteByIdList(idList);
    }

    @Override
    public BlueprintEntity selectInfoById(Integer id) {
        BlueprintEntity entity = blueprintDAO.selectInfoById(id);
        List<BlueprintContent> contents = blueprintContentDao.findBlueprintContentByBlueprintId(id);
        entity.setBlueprintContentList(contents);

        List<BlueprintFileEntity> files = blueprintFileDAO.selectFileByBid(id);
        entity.setFileList(files);

        return entity;
    }

    @Override
    public int updateById(BlueprintEntity record) {
//        Map<String, String> map = new TreeMap<String, String>();
        if (record==null || null == record.getId() || "".equals(record.getId())){
            return 0;
        }
        int num = blueprintDAO.updateByPrimaryKeySelective(record);
        if(num>0){

            //新增明细
            List<BlueprintContent> newContentList = record.getBlueprintContentList();
            List<BlueprintContent> oldContentList = blueprintContentDao.findBlueprintContentByBlueprintId(record.getId());

            //获取旧明细ID集合
            List<Integer> oldIds=oldContentList.stream().map(p -> p.getId()).collect(Collectors.toList());
            //获取新明细ID集合
            List<Integer> newIds=newContentList.stream().map(p -> p.getId()).collect(Collectors.toList());

            if (newIds.size()!=0){
                //获得删除的元素
                oldIds.removeAll(newIds);
            }

            //直接删除明细
            if (oldIds.size()!=0){
                blueprintContentDao.deleteByIds(oldIds);
            }
            for (BlueprintContent p:newContentList){
                if (p.getBlueprintId()==null){
                    p.setBlueprintId(record.getId());
                }
                //判断ID为空则添加，负责修改
                if (p.getId() == null){
                    blueprintContentDao.insertSelective(p);
                }else{
                    blueprintContentDao.updateByPrimaryKeySelective(p);
                }
            }

          /*  List<BlueprintProductEntity> productList = record.getProductList();
            List<BlueprintProductEntity> dbProList = blueprintProductDAO.selectProductByBid(record.getId());//数据库中的产品
            if (!CollectionUtils.isEmpty(dbProList)){
                List<Integer> idList = new ArrayList<Integer>();
                for (BlueprintProductEntity pro : dbProList){
                    idList.add(pro.getId());
                }
                if (idList.size()>0){
                    blueprintProductDAO.deleteByBpId(idList);
                }
            }
            if (!CollectionUtils.isEmpty(productList)){
                for (BlueprintProductEntity  pro: productList){
                    pro.setBlueprintId(record.getId());
                    blueprintProductDAO.insert(pro);
                }
            }*/

            //新增附件
            List<BlueprintFileEntity> fileList = record.getFileList();
            List<BlueprintFileEntity> dbFileList = blueprintFileDAO.selectFileByBid(record.getId());//数据库中的附件
            if (!CollectionUtils.isEmpty(dbFileList)){
                List<Integer> idList = new ArrayList<Integer>();
                for (BlueprintFileEntity pro : dbFileList){
                    idList.add(pro.getId());
                }
                if (idList.size()>0){
                    blueprintFileDAO.deleteByBpId(idList);
                }
            }
            if (!CollectionUtils.isEmpty(fileList)){
                for (BlueprintFileEntity  file: fileList){
                    file.setId(null);
                    file.setBlueprintId(record.getId());
                    file.setFileExecutor(record.getOperator());
                    String fileName = file.getFileName();
                    if(!StringUtils.isEmpty(fileName)){
                        if (StringUtils.isEmpty(file.getFileType())){
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                        }
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    blueprintFileDAO.insert(file);
                }
            }
        }else{
            return 0;
        }
        return num;
    }

    @Override
    public boolean isExist(String number) {
        List<BlueprintEntity> existList = blueprintDAO.isExist(number);
        return CollectionUtils.isEmpty(existList)?false:true;
    }

    @Override
    public int insertInfo(BlueprintEntity record) {
        if(record==null){return 0;}
        int num = blueprintDAO.insert(record);
        if(num>0){
            List<BlueprintProductEntity> productList = record.getProductList();
            if (!CollectionUtils.isEmpty(productList)){
                for(BlueprintProductEntity pro : productList){
                    pro.setBlueprintId(record.getId());
                    blueprintProductDAO.insert(pro);
                }
            }
            List<BlueprintFileEntity> fileList = record.getFileList();
            if (!CollectionUtils.isEmpty(fileList)){
                for(BlueprintFileEntity file : fileList){
                    file.setBlueprintId(record.getId());
                    file.setFileExecutor(record.getOperator());
                    String fileName = file.getFileName();
                    if(!StringUtils.isEmpty(fileName)){
                        if (StringUtils.isEmpty(file.getFileType())){
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                        }
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    blueprintFileDAO.insert(file);
                }
            }
        }
        return num;
    }

    @Override
    public int getCountNum() {
        return blueprintDAO.getCountNum();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public AddBlueprintContentRes add(BlueprintEntity blueprint) {
        Integer num = blueprintDAO.insertSelective(blueprint);
        List<BlueprintContent> blueprintContentList = blueprint.getBlueprintContentList();

        List<MapDetailArray> detailArrays=new ArrayList<>();
        Map<String,List<MapDetailArray>> map=new HashMap<>();
        for (BlueprintContent p: blueprintContentList) {
            if (num!=null){
                p.setBlueprintId(blueprint.getId());
            }else {
                throw new NullPointerException("图纸主信息，新增失败！！");
            }

            blueprintContentDao.insertSelective(p);

            MapDetailArray detailArray=new MapDetailArray();
            detailArray.setId(p.getId().toString());
            detailArray.setTempId(p.getTempId());
            detailArrays.add(detailArray);
        }
        map.put("detailArray",detailArrays);

        AddBlueprintContentRes res=new AddBlueprintContentRes();
        res.setZhuId(num);
        res.setMap(map);
        return res;
    }
}
